package exam.ali;


import java.util.Scanner;
import java.util.*;
//阿里5.7日第二题
public class ex2 {
    static class Node{
        int val;
        Node left;
        Node right;
        Node(int val){
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }

    static Node head = null;
    public static void insert(int num){
        Node cur = head;
        Node pre = null;
        while (cur!=null){
            pre = cur;
            if(num < cur.val){
                cur = cur.left;
            }else{
                cur = cur.right;
            }
        }
        if(num<pre.val){
            pre.left = new Node(num);
        }else{
            pre.right = new Node(num);
        }
    }
    public static void move(Deque<Node> queue,int k ){
        int size = queue.size();
        int []nums = new int[size];
        int []newNums = new int[size];
        for (int i = 0; i < size; i++) {
            Node tempNode = queue.pollFirst();
            nums[i] = tempNode.val;
            queue.addLast(tempNode);
        }
        int j = k%size;
        for (int i = 0; i < size; i++,j++) {
            if(j>=size){
                j=0;
            }
            newNums[i] = nums[j];
        }
        for (int i = 0; i < size; i++) {
            Node tempNode = queue.pollFirst();
            tempNode.val = newNums[i];
            queue.addLast(tempNode);
        }
    }
    public static void dsf(Node root){
        if(root==null){
            return;
        }
        System.out.print(root.val);
        dsf(root.left);
        dsf(root.right);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            int num = scanner.nextInt();
            if(i==0){
                head = new Node(num);
            }else{
                insert(num);
            }
        }
        List<List<Integer>> lists = new LinkedList<>();
        Deque<Node> queue = new ArrayDeque<>();
        queue.addFirst(head);
        while (!queue.isEmpty()){
            move(queue,k); //每一层位移K
            List<Integer> list = new LinkedList<>();
            int size = queue.size();
            for (int i = 0;i<size;i++){
                Node temp = queue.pollFirst();

                if (temp.left != null) {
                    queue.addLast(temp.left);
                }
                if (temp.right != null) {
                    queue.addLast(temp.right);
                }
                list.add(temp.val);
            }
            lists.add(list);
        }

        //层序遍历输出
        for (int i = 0; i < lists.size(); i++) {
            for (int j = 0; j < lists.get(i).size(); j++) {
                System.out.print(lists.get(i).get(j));
            }
            System.out.println();
        }
        dsf(head); //前序遍历输出
    }

}
